<?php

include_once('getDBConnection.php');

$connect = new DBConnection();
$dbc = $connect->getDBC();

	if(isset($_SESSION['user_auth'])){
		//session is set
	}else{
		//session needs to be revalidated
	}

    $query = 'select * from food';

	//if the user passed in a query get the query and store it as $search
	if(isset($_POST['name'])){
            $regex = Constants::regex;
		$search = mysqli_real_escape_string($dbc, $_POST['name']);
                $searchArray = preg_split($regex, $search, -1, PREG_SPLIT_NO_EMPTY);//breaks up each word into its own string and stored results in an array
                for($i=0, $size=sizeof($searchArray);$i<$size;$i++){
                    if($i == 0){
                        $query .= ' where';
                    }
                    $query = $query . " name like ('%" . $searchArray[$i] . "%')";
                    if($i+1 < $size){
                        $query = $query . ' or';
                    }else{
						$query .=";";
					}
                }
	}


	$result = mysqli_query($dbc, $query) or die('An error occurred while trying to query the database: ' . mysqli_error($dbc));

	$return = "<foods>";
	while($row = mysqli_fetch_array($result)){

		$return .= "<food><id>".$row['id']."</id>".
                                        "<type>".$row['type']."</type>".
										"<name>".$row['name']."</name>".
                                        "<calories>".$row['calories']."</calories>".
                                        "<fat>".$row['fat']."</fat>".
                                        "<fiber>".$row['fiber']."</fiber>".
                                        "<points>".$row['points']."</points>".
                                        "<servingSize>".$row['serving_size']."</servingSize>".
                                        "<dateCreated>".$row['date_created']."</dateCreated>".
                                        "<dateModified>".$row['date_modified']."</dateModified>".
                                        "<createdBy>".$row['created_by']."</createdBy></food>";
	}
	$return .= "</foods>";
	print ($return);
	mysqli_close($dbc);
?>
